package org.autumn.shiro;

import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.autumn.util.DigestsUtil;

import java.util.List;
import java.util.stream.Collectors;

public class SiruRealm extends AuthorizingRealm {

    UserService userService = new UserService();

    public SiruRealm() {
        // replace original password matcher
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(DigestsUtil.SHA1);
        matcher.setHashIterations(DigestsUtil.LOOP_ENCRYPTION);
        setCredentialsMatcher(matcher);
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String username = (String) principals.getPrimaryPrincipal();
        List<String> roles = userService.getRoleByName(username);
        List<String> permissions = userService.getPermissionByName(username);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles.stream().collect(Collectors.toSet()));
        info.setStringPermissions(permissions.stream().collect(Collectors.toSet()));
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        DigestsUtil.Digests digests = userService.getPasswordByName(username);
        if (digests == null) {
            throw new UnknownAccountException("unknown account...");
        }
        return new SimpleAuthenticationInfo(username,
                digests.getPassword(),
                ByteSource.Util.bytes(digests.getSalt()),
                getName());
    }
}
